<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Common\File;
use App\Models\Common\Media;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    public function uploadFile(Request $request)
    {
        if ($request->hasFile('upload-file')) {
            $file = $request->file('upload-file');
            $disk = Storage::disk();

            $path = $file->getRealPath();
            $md5 = md5_file($path);
            $ext = $file->getClientOriginalExtension();

            $path1 = substr($md5, 0, 3);
            $path2 = substr($md5, 3, 3);
            $filename = $md5.'.'.$ext;
            $foldpath = 'uploads/file/'.$path1.'/'.$path2.'/';
            $path = $foldpath . $filename;

            $isexist = $disk->exists($path);
            if(!$isexist) {
                $result = $disk->putFileAs($foldpath, $file, $filename);
                if(!$result) {
                    return $this->failJson('file.file_upload_fail');
                }
            }
            $m_file = File::firstOrCreate(
                ['md5'=>$md5],
                [
                    'url'=>$path,
                    'ext'=>$ext,
                    'foldpath'=>$foldpath,
                    'filesize'=>$file->getSize()
                ]
            );

            $url = $disk->url($path);
            Log::debug('url', [$url, env('APP_URL')]);

            $m_media = Media::firstOrCreate(
                [
                    'filename'=>$file->getClientOriginalName(),
                    'url'=>$url,
                    'file_id'=>$m_file->id,
                    'admin_user_id'=>0,
                    'creator_id' => Auth::check() ? Auth::id() : 0,
                ]
            );
            return $this->successJson([
                'id'   => $m_media->id,
                'filename' => $m_media->filename,
                'path' => $foldpath,
                'url'  => $m_media->url,
                'ext'  => $m_file->ext,
            ]);
        } else {
            return $this->failJson('file.file_form_not_exist');
        }
    }
}
